import { FC, ReactElement, useCallback, useEffect, useReducer } from 'react';
import { todoReducer } from '../../Reducer/todoList/reducer';
import { IState, ITodo, TODO_ACTION_TYPE } from './typings';
import TdInput from './Input';
import TdList from './List';

const initialState: IState = {
  todoList: []
};

const TodoList: FC = (): ReactElement => {
  const [state, dispatch] = useReducer(todoReducer, initialState);

  useEffect(() => {
    console.log(state.todoList);
  }, [state.todoList]);

  const addTodo = useCallback((todo: ITodo) => {
    dispatch({
      type: TODO_ACTION_TYPE.ADD_TODO,
      payload: todo
    });
  }, []);

  const removeTodo = useCallback((id: number) => {
    dispatch({
      type: TODO_ACTION_TYPE.REMOVE_TODO,
      payload: id
    });
  }, []);

  const toggleTodo = useCallback((id: number) => {
    dispatch({
      type: TODO_ACTION_TYPE.TOGLE_TODO,
      payload: id
    });
  }, []);

  return (
    <div className={'todo-list_container'}>
      <TdInput addTodo={addTodo} todoList={state.todoList} />
      <TdList
        todoList={state.todoList}
        removeTodo={removeTodo}
        toggleTodo={toggleTodo}
      />
    </div>
  );
};
export default TodoList;
